//
//  MineViewController.m
//  OneDay
//
//  Created by lanou3g on 15/11/10.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "MineViewController.h"
#import "CollectionTableViewController.h"
#import "AboutOursViewController.h"
#import "LoginViewController.h"

@interface MineViewController ()

@property (nonatomic, strong) UIView *collectionView;

@property (nonatomic, strong) UIView *designView;

@property (nonatomic, assign) BOOL havaOrNot;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:202.67 / 255.0 green:235.17 / 255.0 blue:216.58 / 255.0 alpha:1];
    self.navigationItem.title = @"我的地盘我做主";
    self.tableView.backgroundColor = [UIColor colorWithRed:202.67 / 255.0 green:235.17 / 255.0 blue:216.58 / 255.0 alpha:1];
    self.tableView.scrollEnabled = NO;
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self addTableHeaderView];
    [self collectionButton];
    [self addDesignButton];
    
}

#pragma mark - 添加tableview的表头
- (void)addTableHeaderView
{
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kWidth * 0.6)];
    bgImageView.image = [UIImage imageNamed:@"login"];
    self.tableView.tableHeaderView = bgImageView;
    CGFloat size = bgImageView.height - 60;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size, size)];
    view.center = bgImageView.center;
    [bgImageView addSubview:view];
    UIImageView *loginImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, view.height - 40, view.height - 40)];
    loginImageView.image = [UIImage imageNamed:@"iconfont-bqklt-2"];
    [view addSubview:loginImageView];
    
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake(0, loginImageView.bottom + 10, 60, 30);
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [view addSubview:loginButton];
    
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.frame = CGRectMake(size - 60, loginImageView.bottom + 10, 60, 30);
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [registerButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [view addSubview:registerButton];
}

#pragma mark - 添加收藏按钮
- (void)collectionButton
{
    if (self.havaOrNot) {
        [self.collectionView removeFromSuperview];
        self.havaOrNot = NO;
    } else {
        
        self.collectionView = [[UIView alloc] initWithFrame:CGRectMake(kWidth * 0.3, kHeight * 0.2, kWidth * 0.4, kHeight * 0.3)];
        self.collectionView.backgroundColor = [UIColor blackColor];
        
        NSArray *titleArray = @[@"我的活动", @"我的影集", @"我的旅游", @"美文收藏"];
        for (int i = 0; i < 4; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, kHeight * 0.3 / 4 * i, kWidth * 0.4, kHeight * 0.3 / 4 - 1);
            button.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:183 / 255.0 blue:183 / 255.0 alpha:1];
            button.tag = 2015 + i;
            [button setTitle:titleArray[i] forState:UIControlStateNormal];
            [self.collectionView addSubview:button];
            
            self.havaOrNot = YES;
        }
        
    }
    
}

#pragma mark - 添加设置按钮
- (void)addDesignButton
{
    self.designView = [[UIView alloc] initWithFrame:CGRectMake(kWidth * 0.3, kHeight * 0.4, kWidth * 0.4, kHeight * 0.225)];
    self.designView.backgroundColor = [UIColor blackColor];
    
    NSArray *titleArray = @[@"当前版本", @"关于我们", @"免责声明"];
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, kHeight * 0.3 / 4 * i, kWidth * 0.4, kHeight * 0.3 / 4 - 1);
        button.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:183 / 255.0 blue:183 / 255.0 alpha:1];
        button.tag = 4018 + i;
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [self.designView addSubview:button];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"reuseIdentifier"];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor brownColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"我的收藏";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-shoucang"];
    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"清除缓存";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-lajixiang"];
    } else if (indexPath.row == 2) {
        cell.textLabel.text = @"设置";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-ordinaryset"];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        [self.view addSubview:self.collectionView];
        CATransition *animation = [CATransition animation];
        animation.duration = 1.5;
        animation.type = @"rippleEffect";
        animation.subtype = kCATransitionFromTop;
        animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
        [self.collectionView.layer addAnimation:animation forKey:@"animation"];
        
        for (int i = 0; i < 4; i++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:2015 + i];
            [button addTarget:self action:@selector(pushNextVC:) forControlEvents:UIControlEventTouchUpInside];
        }
    } else if (indexPath.row == 1) {
        NSString * cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        float HCSize = [self folderSizeAtPath:cachPath];
        NSString *str=[NSString stringWithFormat:@"\n 当前缓存大小:%.1fM,是否确定清理缓存?", HCSize];
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alertView show];
    } else {
        [self.view addSubview:self.designView];
        CATransition *animation = [CATransition animation];
        animation.duration = 1.5;
        animation.type = @"cameraIrisHollowOpen";
        animation.subtype = kCATransitionFromTop;
        animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
        [self.designView.layer addAnimation:animation forKey:@"animation"];
        for (int i = 0; i < 4; i++) {
            UIButton *button = (UIButton *)[self.view viewWithTag:4018 + i];
            [button addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}
#pragma marks -- UIAlertViewDelegate --
// 清除缓存
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSString * cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *contents = [fileManager contentsOfDirectoryAtPath:cachPath error:NULL];
        NSEnumerator *e
        = [contents objectEnumerator];
        NSString *filename;
        while ((filename = [e nextObject])) {
            [fileManager removeItemAtPath:[cachPath stringByAppendingPathComponent:filename] error:NULL];
        }
    }
}

- (void)pushNextVC:(UIButton*)sender
{
    DataManager *manager = [DataManager shareManager];
    // 判断是否登录
    if ([manager isLogin] == NO) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        // 实现block
        loginVC.block = ^void(){
            NSLog(@"登录成功");
        };
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navC animated:YES completion:nil];
    }else{
        CollectionTableViewController *collectVC = [[CollectionTableViewController alloc] init];
        collectVC.currentIndex = sender.tag - 2015 + 1;
        [self.navigationController pushViewController:collectVC animated:YES];
    }
    
}

- (void)actionButton:(UIButton *)sender
{
    if (sender.tag == 4018) {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"OneDay" message:@"当前版本：1.0.1，已是最新版本" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alertView show];
        // 实现 2 秒回收
        [self performSelector:@selector(actionAlert:) withObject:alertView afterDelay:2];
    } else {
        AboutOursViewController *aboutVC  = [[AboutOursViewController alloc] init];
        aboutVC.num = sender.tag - 4018 + 2;
        [self.navigationController pushViewController:aboutVC animated:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self collectionView];
    [self addDesignButton];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.collectionView removeFromSuperview];
    [self.designView removeFromSuperview];
}

#pragma mark - 添加手势去除收藏弹框
- (void)addTapGesture
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTap)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap];
}

- (void)actionTap
{
    [self.collectionView removeFromSuperview];
}


#pragma mark -- 计算文件大小，用于清除缓存
- (float )folderSizeAtPath:(NSString*) folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
//单个文件的大小
- (float) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}

#pragma mark -- 实现2秒消失
- (void)actionAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];// 三秒回收
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma CATransition动画实现
- (void)changeAnimationWithType:(NSString *)type WithSubtype:(NSString *) subtype ForView:(UIView *) view
{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    
    //设置运动时间
    animation.duration = 1;
    
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
        
        //设置子类
        animation.subtype = subtype;
    }
    
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    
    [view.layer addAnimation:animation forKey:@"animation"];
}


@end
